import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  ListView,
  Image,
  TextInput,
  TouchableOpacity,
  Platform,
  Picker,
  InteractionManager,
  DeviceEventEmitter,
  ActivityIndicator,
  Dimensions,
  NativeAppEventEmitter
} from 'react-native';

import * as config from '../../constants/apiConfig';
import styles from './hkInfoStyle';
import moment from 'moment';
import api from '../../services/api';
import helper from '../util/helper';
import Toast from 'react-native-sk-toast';
import ImagePicker from 'react-native-image-crop-picker';

import ToastTip from '../global/ToastTip';
import LoadingTip from '../global/LoadingTip';
import KeyboardAwareScrollView from '../global/keyboardScrollView/KeyboardAwareScrollView';
import Touch from '../global/Touch';
import AsyncSession from '../../services/AsyncSession';

const Screen = Dimensions.get('window');

class HkInfo extends Component {
    constructor(props) {
		super(props);

        this.state = {
            reward_score: -1,
            rank: '0/0',
            flag_ardour: 0,
            flag_capable:0,
            flag_witty:0,
            flag_intimate:0,
            evaluationCount: -1,
            list: [],
            keeper_head: '',
            isLoadingMore: true,
            isRefreshing: false,
            loadingShow: true
		};

        this.evaluationList = [];
        this.totalCount = 0;
        this._pageSize = 10;

		// this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
	}

    componentDidMount(){
        // let { session } = this.props;
        // if( session ) {
        //     this.setState({
        //         keeper_head: session.user.keeper_head
        //     });
        // }
        InteractionManager.runAfterInteractions(() => {
            this._getHKSummary(1);
        });

    }

    async _getHKSummary(page){
        let res = await api.post("/order/getOwnerServiceSummary",{page, pagesize: this._pageSize});
        console.log('test_getHKSummary_getHKSummary_getHKSummary_getHKSummary_getHKSummary_getHKSummary',res);
        if(res.cd == 0){
            if(page == 1){
                this.evaluationList = res.data.evaluationList;
            }else {
                for (var i = 0; i < res.data.evaluationList.length; i++) {
                    this.evaluationList.push(res.data.evaluationList[i]);
                }
            }

            this.totalCount = res.data.evaluationCount;

            this.setState({
                reward_score: res.data.reward_score,
                rank: res.data.rank,
                flag_ardour: res.data.flag_ardour,
                flag_capable: res.data.flag_capable,
                flag_witty: res.data.flag_witty,
                flag_intimate: res.data.flag_intimate,
                evaluationCount: res.data.evaluationCount,
                list: this.evaluationList,
                isLoadingMore: false,
                loadingShow: false
            });

        }
    }

    _renderRow(rowData, sectionID, rowID){

        return (
            <View style={styles.hkItem} key={rowID}>
                <View style={styles.topLine}>
                    {rowData.wxHeader?<Image source={{uri: rowData.wxHeader}} style={styles.headEvalImage} />:<Image source={require('../../../img/def_avert.png')} style={styles.headEvalImage}/>}
                    <View style={styles.nameContainer}>
                        <View style={styles.nameAndStarContainer}>
                            <Text style={styles.name}>{rowData.name?rowData.name:(rowData.wxName?rowData.wxName:'匿名')}</Text>
                            <View style={styles.smallStarContainer}>
                                {this._renderSmallStar(rowData.reward_score)}
                            </View>
                        </View>
                        <Text style={styles.time}>{rowData.order_reward_time}</Text>
                    </View>
                </View>
                <View style={styles.bottomLine}>
                    <Text style={styles.content}>{rowData.reward_evaluate}</Text>
                </View>
            </View>
        );
    }

    _renderFooter(){
        // let {notRenderFooter} = this.state;
        if(this.totalCount<=this._pageSize){
            return null;
        };

        if(this.evaluationList.length < this.totalCount){
            return (
                <View style={styles.footer}>
                    <Text style={styles.footerTitle}>{'正在加载更多……'}</Text>
                </View>
            );
        }else {
            return (
                <View style={styles.footer}>
                    <Text style={styles.footerTitle}>{'已经到底啦'}</Text>
                </View>
            )
        }

    }

    async _endReached(){
        let {isLoadingMore, isRefreshing} = this.state;

        if (isLoadingMore || this.evaluationList.length >= this.totalCount || isRefreshing) {
			console.log("return 了");
			return;
		};

        this.setState({
            isLoadingMore: true,
        });

        let _pageNo = parseInt(this.evaluationList.length / this._pageSize) + 1;

        await this._getHKSummary(_pageNo);

        this.setState({
            isLoadingMore: false
        });

    }

    componentWillUnmount(){
        // let {dispatch, actions} = this.props;

        // dispatch(actions.card.card_name_change(''));
        // dispatch(actions.card.card_province_change(''));
        // dispatch(actions.card.card_city_change(''));
    }

    _selectPerson(){
        ImagePicker.openPicker({
          width: 250,
          height: 350,
          cropperCircleOverlay: true,
          includeBase64: true,
          compressImageQuality: 0.4,
          mediaType: 'photo',
          cropping: true
       }).then(async(image) => {
            if(image.data){
                let base64 = 'data:image/jpeg;base64,' + image.data;
                let res = await api.post("/housekeeper/changeHead",{keeper_head: base64});
                if(res.cd == 0){
                    let { session, actions, dispatch } = this.props;
                    let copySession = {...session};
                    copySession.user.keeper_head = base64;

                    setTimeout(function(){
                        //更新本地缓存
                        // dispatch(actions.session.session_data_change(copySession));
                        AsyncSession.saveTokenAndUser(copySession.stoken, copySession.user);
                    }, 100);

                    this.setState({
                        keeper_head: base64
                    });

                    Toast.bottom('头像修改成功');
                }else {
                    Toast.bottom('更换头像失败，请重试');
                }

            }

        });
    }

    _renderStar(score){
        let starComp = [];
        for (var i = 0; i < score; i++) {
            starComp.push(<Image key={i} source={require('../../../img/hk_star_active_icon.png')} style={styles.starImage}/>);
        }
        for (var i = 0; i < 5-score; i++) {
            starComp.push(<Image key={5+i} source={require('../../../img/hk_star_icon.png')} style={styles.starImage}/>);
        }

        return starComp;
    }

    _renderSmallStar(score){
        let starComp = [];
        for (var i = 0; i < score; i++) {
            starComp.push(<Image key={i} source={require('../../../img/hk_small_active_star_icon.png')} style={styles.smallstarImage}/>);
        }
        for (var i = 0; i < 5-score; i++) {
            starComp.push(<Image key={5+i} source={require('../../../img/hk_small_star_icon.png')} style={styles.smallstarImage}/>);
        }

        return starComp;
    }

    render() {
        const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

        let { reward_score, rank, flag_ardour, flag_capable, flag_witty, flag_intimate, evaluationCount, list, keeper_head } = this.state;
        let { session } = this.props;
        if(!session){
            return null;
        }

        return (
            <View style={[styles.wrapper,{backgroundColor:'#f3f3f3'}]}>
                <KeyboardAwareScrollView style={styles.container} extraScrollHeight={60}>
                    <View style={styles.addressContainer}>
                        <Touch style={[styles.formItem, {justifyContent: 'space-between', paddingRight: 15, height: 65}]} onPress={this._selectPerson.bind(this)}>
                            <Text style={[styles.leftText, {flex:1}]}>我的头像</Text>
                            {keeper_head?<Image style={[styles.headImage,styles.rightImage,{marginRight:10}]} source={{uri: session.user.keeper_head}} />:
                            <Image style={[styles.headImage,styles.rightImage,{marginRight:10}]} source={{uri: session.user.keeper_head}} />}
                            <Image source={require('../../../img/hk_arrow_icon.png')}/>
                        </Touch>

                        {
                            session.user.isShop == 1 ? 
                                null 
                            : 
                                <View style={[styles.formItem,{borderBottomWidth:0}]}>
                                    <Text style={[styles.leftText,{flex:1}]}>当月排名</Text>
                                    <Text style={[styles.rightText,{marginRight: 15, color: "#565656", fontSize: 15}]}>
                                        <Text style={styles.sprText}>
                                            {
                                                rank && rank.split('/') && rank.split('/').length == 2?
                                                    rank.split('/')[0]!='0'?
                                                        rank.split('/')[0]
                                                    :
                                                        '--'
                                                :
                                                    '--'
                                            }
                                        </Text>/
                                        {
                                            rank && rank.split('/') && rank.split('/').length == 2?
                                                rank.split('/')[1]
                                            :
                                                '--'
                                        }
                                    </Text>
                                </View>
                        }
                        
                    </View>
                    {reward_score?
                    <View>
                        <View style={styles.formContainer}>
                        <View style={styles.scoreAndTag}>
                            <View style={styles.countContent}>
                                <Text style={styles.leftTitleText}>我的总评分</Text>
                                <View style={{alignItems:'center'}}>
                                    <View style={styles.starContainer}>
                                        {this._renderStar(reward_score)}
                                    </View>
                                </View>
                            </View>

                            <View style={styles.tagContent}>
                                <Text style={[styles.leftTitleText,{marginLeft:0}]}>我的标签</Text>
                                <View style={[styles.tagContainer,{paddingLeft:0}]}>
                                    <Text style={styles.notActiveText}>热情 {flag_ardour>999999?(999999+'+'):flag_ardour}</Text>
                                    <Text style={styles.notActiveText}>干练 {flag_capable>999999?(999999+'+'):flag_capable}</Text>
                                    <Text style={styles.notActiveText}>机智 {flag_witty>999999?(999999+'+'):flag_witty}</Text>
                                    <Text style={styles.notActiveText}>贴心 {flag_intimate>999999?(999999+'+'):flag_intimate}</Text>
                                </View>
                            </View>
                        </View>
                    </View>
                    {evaluationCount?<View style={styles.formContainer}>
                        <Text style={[styles.leftTitleText, {borderColor:'#DDDDDD', borderBottomWidth: StyleSheet.hairlineWidth,paddingBottom:15}]}>评价 ({evaluationCount})</Text>
                        <View style={styles.listContainer}>
                            <ListView
                                enableEmptySections={true}
                                dataSource={ds.cloneWithRows(this.state.list)}
                                pageSize={10}
                                initialListSize={10}
                                renderRow={this._renderRow.bind(this)}
                                renderFooter={this._renderFooter.bind(this)}
                                onEndReached={this._endReached.bind(this)}
                                onEndReachedThreshold={10}
                                />
                        </View>
                    </View>:null}
                </View>:null}
                </KeyboardAwareScrollView>

                <ToastTip ref="toast" offsetY={160}/>
                {this.state.loadingShow?
                <View style={[styles.loadContainer, {bottom:(Screen.height - 60) / 2}]}>
                    <ActivityIndicator size="small" color={Platform.OS === "ios" ? "#f3f3f3" : "#EA0000"} />
                </View>:null}
            </View>
        );
    }
}

var connectHelper = require('../../services/connectHelper');
HkInfo = connectHelper(state => state)(HkInfo);

module.exports = HkInfo;
